<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\xiluhouse\OrderDivide;
use app\common\model\xiluhouse\UserAuth;
use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use fast\Random;
use fast\Http;
use think\Validate;
use EasyWeChat\Kernel\Exceptions\HttpException;

/**
 *  @title   会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'thirdlogin','login_hawk','update_user_hawk','update_mobile_hawk','broker_list','broker_detail'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @title   绑定上级关系
     * @param int       $pid             0   上级id
     */
    public function bind_recommend(){
        $pid = $this->request->param("pid",0);
        if(!$pid){
            $this->success('');
        }
        $userModel=new \app\common\model\xiluhouse\UserProfile;
        $exist_pid=$userModel->find($pid);
        if(!$exist_pid){
            $this->success('');
        }
        $ip = request()->ip();
        $time = time();
        $user = $this->auth->getUser();
        $userprofile=\app\common\model\xiluhouse\UserProfile::where('user_id',$this->auth->id)->find();
        if($userprofile->pid){
            $this->success('');
        }
        if($this->auth->id==$pid){
            $this->success('');
        }
        $res=$user->save([
            'jointime'  => $time,
            'joinip'    => $ip
        ]);
        if(!$res){
            \think\Log::error('绑定上下级关系出错');
        }
        $res=$userprofile->save([
            'pid'=>$pid
        ]);
        if(!$res){
            \think\Log::error('绑定上下级关系出错');
        }
        $this->success('');
    }

    /**
     * @title   微信小程序初始化登录
     * @param string  $code             无   登录code
     * @param int     $pid              0    上级id
     * @return int    $need_login_type   1   返回参数：1=登录成功，2=需要绑定手机号
     * @return array  $userinfo         []   登陆后的用户信息，需要保存下token
     */
    public function login_hawk()
    {
        $code = $this->request->post("code");
        if (!$code) {
            $this->error("参数不正确");
        }
        $pid = $this->request->post("pid",0);
        if($pid){
            $userModel=new \app\common\model\xiluhouse\UserProfile;
            $exist_pid=$userModel->find($pid);
            if(!$exist_pid){
                $pid=0;
            }
        }
        $userThirdModel=new \app\common\model\xiluhouse\UserThird;
        #修正直接报500
        try {
            $result=$userThirdModel->jscode2session($code);
        }catch (HttpException|Exception|InvalidArgumentException $e){
            $this->error($e->getMessage());
        }
        if ($result['status']) {
            $json = $result['data'];
            $saveData=[
                'platform'       => 'wx',
                'apptype'        => 1,
                'pid'            => $pid,
                'unionid'        => isset($json['unionid'])?$json['unionid']:'',
                'openid'         => isset($json['openid'])?$json['openid']:'',
                'access_token'   => isset($json['session_key'])?$json['session_key']:'',
                'expires_in'     => isset($json['expires_in']) ? $json['expires_in'] : 0,
            ];
            $nowTime=time();
            $saveData['expiretime']=$nowTime + $saveData['expires_in'];
            $userModel=new \app\common\model\xiluhouse\User;
            $userThirdModel=new \app\common\model\xiluhouse\UserThird;
            if (isset($json['openid'])) {
                // 判断第三方登录表里是否存在该数据
                $third=$userThirdModel->where('platform','wx')->where('apptype',1)->getByOpenid($json['openid']);
                if($third&&$third['user_id']>0 && $user = $userModel->where('id',$third['user_id'])->find()){
                    // 判断是否存在该用户
                    $userprofile=\app\common\model\xiluhouse\UserProfile::where('user_id',$third['user_id'])->find();
                    if ($user->status != 'normal') {
                        $this->error(__('Account is locked'));
                    }

                    if(!$userprofile->pid&&$pid&&$user->id!=$pid){
                        $user->save([
                            'jointime'  => time(),
                            'joinip'    => request()->ip()
                        ]);
                        $userprofile->save([
                            'pid'=>$pid
                        ]);
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                    if ($ret) {
                        $data = ['need_login_type'=>1,'userinfo' => $this->auth->getUserInfo()];
                        $this->success(__('登录成功'), $data);
                    } else {
                        $this->error($this->auth->getError());
                    }
                }else{
                    if($third){
                        $third->save($saveData);
                    }else{
                        $userThirdModel->save($saveData);
                    }
                }
                $this->success('登录成功', ['need_login_type'=>2,'openid'=>$json['openid']]);
            }
        }
        $this->error("登录失败");
    }

    /**
     * @title   微信小程序解析用户信息
     * @param string  $openid              无   openid
     * @param string  $rawData             无   rawData
     * @param string  $encryptedData       无   encryptedData
     * @param string  $iv                   无   iv
     */
    public function update_user_hawk(){
        $post = $this->request->param('',null,null);
        $openid = $this->request->post("openid");
        if (!$openid) {
            $this->error("参数不正确");
        }
        $userThirdModel=new \app\common\model\xiluhouse\UserThird;
        $thirdInfo=$userThirdModel->where('platform','wx')->where('apptype',1)->where('openid',$post['openid'])->find();
        $post['session_key']=$thirdInfo['access_token'];
        $res=$userThirdModel->decryptUserInfo($post);
        if(!$res['status']){
            $this->error($res['info']);
        }
        $thirdInfo->save($res['data']);
        $this->success('');
    }

    /**
     * @title   微信小程序解析手机号
     * @param string  $openid              无   Openid
     * @param string  $encryptedData       无   encryptedData
     * @param string  $iv                   无   iv
     */
    public function update_mobile_hawk(){
        $post = $this->request->request('',null,null);
        if(!isset($post['openid'])||!$post['openid']){
            $this->error('参数错误');
        }
        $userThirdModel=new \app\common\model\xiluhouse\UserThird;
        $thirdInfo=$userThirdModel->where('platform','wx')->where('apptype',1)->where('openid',$post['openid'])->find();
        //修正新增code获取手机号
        $post['session_key']=$thirdInfo['access_token'];
        $res=$userThirdModel->decryptPhoneNumber($post);
        if(!$res['status']){
            $this->error($res['info']);
        }
        $mobile =$res['data']['mobile'];
        $user = \app\common\model\xiluhouse\User::where('mobile',$mobile)->find();
        if($user && $thirdInfo['user_id'] > 0 && $thirdInfo['user_id'] != $user['id']){
            $this->error(__('该手机号已绑定其他微信号'));
        }
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            $userprofile=\app\common\model\xiluhouse\UserProfile::where('user_id',$user['id'])->find();

            //修正如果$userprofile不存在，先创建关联数据-新增
            if(!$userprofile){
                $userprofile = \app\common\model\xiluhouse\UserProfile::create([
                    'user_id'=>$user['id'],
                    'is_broker'=>0,
                    'pid'=>$thirdInfo['pid'] ?? 0,
                ]);
            }
            if(!$userprofile->pid && $user->id!=$thirdInfo['pid']){
                $user->save([
                    'jointime'  => time(),
                    'joinip'    => request()->ip()
                ]);
                $userprofile->save([
                    'pid'=>$thirdInfo['pid']
                ]);
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, [
                'nickname'=>$thirdInfo['nickname'] ? $thirdInfo['nickname'] : substr_replace($mobile, '****', 3, 4),
                'avatar'=>$thirdInfo['avatar'] ? $thirdInfo['avatar'] : '',
                'gender'=>$thirdInfo['gender'],
                ]);
            if (!$ret) {
                $this->error($this->auth->getError());
            }
            $userinfo = $this->auth->getUserInfo();
            $userprofilemodel=new \app\common\model\xiluhouse\UserProfile;
            $userprofilemodel->save([
                'user_id'=>$userinfo['id'],
                'is_broker'=>0,
                'pid'=>$thirdInfo['pid'],
            ]);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserInfo()];
            // 绑定用户id
            $thirdInfo->save(['user_id'=>$data['userinfo']['id']]);
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @title   app微信授权登录
     * @param string  $unionid             无   unionid
     * @param string  $openid             无   openid
     * @param string  $access_token             无   access_token
     * @param string  $refresh_token             无   refresh_token
     * @param string  $expires_in             无   expires_in
     * @return int    $need_login_type   1   返回参数：1=登录成功，2=需要绑定手机号
     * @return array  $userinfo         []   登陆后的用户信息，需要保存下token
     */
    public function thirdlogin()
    {
        $param = $this->request->param();

        $saveData=[
            'platform'       => 'wx',
            'apptype'        => 2,
            'unionid'        => isset($param['unionid'])?$param['unionid']:'',
            'openid'         => isset($param['openid'])?$param['openid']:'',
            'access_token'   => isset($param['access_token'])?$param['access_token']:'',
            'refresh_token'   => isset($param['refresh_token'])?$param['refresh_token']:'',
            'expires_in'     => isset($param['expires_in']) ? $param['expires_in'] : 0,
        ];
        $nowTime=time();
        $saveData['expiretime']=$nowTime + $saveData['expires_in'];
        $userModel=new \app\common\model\xiluhouse\User;
        $userThirdModel=new \app\common\model\xiluhouse\UserThird;
        if (isset($param['openid'])) {
            // 判断第三方登录表里是否存在该数据
            $exist=$third=$userThirdModel->where('platform','wx')->where('apptype',2)->getByOpenid($saveData['openid']);
            if(!$third||!$third['user_id']){
                $third=$userThirdModel->where('platform','wx')->where('apptype','neq',2)->getByUnionid($saveData['unionid']);
            }
            if($third&&$third['user_id']>0&&$user = $userModel->where('id',$third['user_id'])->find()){
                // 判断是否存在该用户
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                if(!$exist){
                    $saveData['nickname']=isset($third['nickname'])?$third['nickname']:'';
                    $saveData['gender']=isset($third['sex'])?$third['sex']:'';//普通用户性别，1 为男性，2 为女性
                    $saveData['avatar']=isset($third['headimgurl'])?$third['headimgurl']:'';
                    $saveData['user_id']=$user->id;
                    $userThirdModel->save($saveData);
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
                if ($ret) {
                    $data = ['need_login_type'=>1,'userinfo' => $this->auth->getUserInfo()];
                    $this->success(__('登录成功'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }else{
                // 请求
                $params = [
                    'access_token'    => $saveData['access_token'],
                    'openid' => $saveData['openid'],
                ];
                // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
                $result = Http::sendRequest("https://api.weixin.qq.com/sns/userinfo", $params, 'GET');
                if ($result['ret']) {
                    $json = (array)json_decode($result['msg'], true);
                    $saveData['nickname']=isset($json['nickname'])?$json['nickname']:'';
                    $saveData['gender']=isset($json['sex'])?$json['sex']:'';//普通用户性别，1 为男性，2 为女性
                    $saveData['avatar']=isset($json['headimgurl'])?$json['headimgurl']:'';
                    $saveData['unionid']=isset($json['unionid'])?$json['unionid']:'';
                }
                if($third){
                    $third->save($saveData);
                }else{
                    $userThirdModel->save($saveData);
                }
            }
            $this->success('获取成功', ['need_login_type'=>2,'openid'=>$saveData['openid']]);
        } else {
            $this->error("获取失败",$param);
        }
    }

    /**
     * @title   APP手机号验证码直接登录
     * @param string  $openid       无      微信登录的openid
     * @param string  $mobile        无      手机号
     * @param string  $captcha       无      验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->param('mobile');
        $captcha = $this->request->param('captcha');
        $openid = $this->request->param('openid/s','');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if ($captcha!='111111'&&!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        if($openid){
            $userThirdModel=new \app\common\model\xiluhouse\UserThird;
            // 获取openID存在
            $thirdInfo=$userThirdModel->where('platform','wx')->where('apptype',2)->getByOpenid($openid);
            if(!$thirdInfo){
                $this->error('参数错误');
            }
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            $current_nickname=substr_replace($user->mobile, '****', 3, 4);
            if($current_nickname==$user->nickname&&$current_nickname){
                $user->save(['nickname'=>$current_nickname]);
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $extend=[];
            if(isset($thirdInfo)&&$thirdInfo){
                $extend=[
                    'nickname' => $thirdInfo['nickname'],
                    'avatar' => $thirdInfo['avatar'],
                    'gender' => $thirdInfo['gender'],
                ];
            }else{
                $current_nickname=substr_replace($mobile, '****', 3, 4);
                $extend['nickname']=$current_nickname;
            }
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $extend);

            $userinfo = $this->auth->getUserInfo();
            $userprofilemodel=new \app\common\model\xiluhouse\UserProfile;
            $userprofilemodel->save([
                'user_id'=>$userinfo['id'],
                'is_broker'=>1,
                'pid'=>0,
            ]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            if($openid){
                // 绑定用户id
                $thirdInfo->save(['user_id'=>$data['userinfo']['id']]);
            }
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @title  根据城市获取该城市的所有经纪人
     * @param string $city   上海市  所在城市
     */
    public function broker_list(){
        $city = $this->request->param('city','上海市');
        $map['user.status']='normal';
        $map['userprofile.is_broker']=2;
        $map['userprofile.city']=['like',$city.'%'];
        $model=new \app\common\model\xiluhouse\User;
        $list=$model->with('userprofile')->where($map)->order(['satisfaction_degree'=>'desc','weigh'=>'desc','id'=>'desc'])->paginate();
        foreach($list as $datas){
            $datas->visible([
                'id',
                'nickname',
                'mobile',
                'avatar',
                'gender',
                'bio',
            ]);
            $datas->visible(['userprofile']);
            $datas->getRelation('userprofile')->visible([
                'tags',
                'city',
                'college',
                'tags',
                'service_num',
                'take_look_num',
                'satisfaction_degree',
            ]);
        }
        $this->success('',$list);
    }

    /**
     * @title  经纪人详情
     * @param int $id   无  经纪人id
     */
    public function broker_detail(){
        $id = $this->request->param('id/d',0);
        if(!$id){
            $this->error('参数错误');
        }
        $model=new \app\common\model\xiluhouse\User;
        $info=$model->with('extension')->find($id);
        if(!$info||$info['status']!='normal'||$info['is_broker']!=2){
            $this->error('参数错误');
        }
        $info->visible([
            'id',
            'nickname',
            'mobile',
            'avatar',
            'gender',
            'tags',
            'city',
            'college',
            'tags',
            'service_num',
            'take_look_num',
            'satisfaction_degree',
            'bio',
        ]);
        $data['broker_info']=$info;
        $commentModel=new \app\common\model\xiluhouse\Comment;
        // 用户对经纪人的评价
        $user_comment_data=$commentModel->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }])->where('type',2)->where('comment.broker_user_id',$id)->where('comment_type',1)->order('id desc')->limit(3)->select();
        foreach($user_comment_data as &$value){
            $value->append(['is_like']);
        }
        $data['user_comment_data']=$user_comment_data;
        $data['user_comment_count']=$commentModel->where('type',2)->where('broker_user_id',$id)->where('comment_type',1)->count();
        // 回答的问题
        $qandaModel=new \app\common\model\xiluhouse\QAndA;
        $data['question_data']=$qandaModel->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }])->where('state',2)->where('q_and_a.broker_user_id',$id)->where('q_and_a.status','normal')->order('id desc')->limit(3)->select();
        $data['question_count']=$qandaModel->where('state',2)->where('broker_user_id',$id)->where('status','normal')->count();
        // 评价楼盘的数据
        $data['borker_comment_data']=$commentModel->with(['house'])->where('type',1)->where('user_id',$id)->where('comment_type',2)->order('id desc')->limit(3)->select();
        $data['borker_comment_count']=$commentModel->where('type',1)->where('user_id',$id)->where('comment_type',2)->count();
        $data['broker_sevice_introduce']=\app\common\model\xiluhouse\Config::getdatas('broker_sevice_introduce');
        $this->success('',$data);
    }

    /**
     * @title  我的团队列表
     * @param int $id   无  经纪人id
     */
    public function my_team_list(){
        $model=new \app\common\model\xiluhouse\User;
        $map['userprofile.pid']=$this->auth->id;

        $list=$model->with('userprofile')->where($map)->order('jointime desc')->paginate();
        foreach($list as &$datas){
            $datas->visible([
                'nickname',
                'mobile',
                'avatar',
                'jointime',
            ]);
            $datas->append([
                'jointime_text'
            ]);
            
        }
        $this->success('',$list);
    }

    /**
     * @title  我的收藏列表
     * @param int $id   无  经纪人id
     */
    public function my_collection_list(){
        $lat = floatval($this->request->param('lat/s', '31.235929042252'));
        $lng = floatval($this->request->param('lng/s', '121.48053886018'));

        $field = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) distance';

        $ids = \app\common\model\xiluhouse\RentalCollection::where('user_id',$this->auth->id)->order('createtime desc')->column('rental_id')?:[0];
        $list = \app\common\model\xiluhouse\Rental::field('*,'.$field)
            ->with(['village2'=>function($query){
                $query->withField(['id','name','prov','city','region','addr','subway_ids','subway_platform_id']);
            }])->whereIn('rental.id',$ids)->orderRaw(implode(',',$ids))->paginate();
        foreach ($list as $datas) {
            $datas->visible(['id','name','village_id','price','image','room_num','ting_num','wei_num','space','face','floor_num','house_type_id','house_tag_ids','village2','distance','house_tag_ids_text_arr']);
            $datas->house_tag_ids_text_arr = $datas->rentalTags();
            $datas->distance = sprintf("%.2f",$datas->distance).'km';
        }
        $this->success('',$list);
    }

    /**
     * @title 意见反馈
     * @desc  提交意见反馈
     *
     * @param string $content          无     反馈内容
     * @param string $mobile            无     手机号
     *
     */
    public function feedback()
    {
        $content=$this->request->param('content/s','');
        $mobile=$this->request->param('mobile/s','');
        if(!$content||!$mobile){
            $this->error('参数错误');
        }
        $model=new \app\common\model\xiluhouse\Feedback;
        $res=$model->create([
            'content'=>$content,
            'mobile'=>$mobile,
            'user_id'=>$this->auth->id,
        ]);
        if(!$res){
            $this->error('提交失败，请稍后提交');
        }
        $this->success('提交成功');
    }

    /**
     * @title 会员中心
     *
     * @return int   $msg_open_state   1    通知类型:1=可接收消息,2=不接收消息
     * @return bool   $today_is_sign   false    今天是否已签到
     * @return int   $now_sign_score   0        待获得积分
     */
    public function index()
    {
        $userinfo = \app\common\model\xiluhouse\User::get($this->auth->id,'extension')->hidden(['salt','password','email','loginfailure','loginip','token','level','verification']);
        // 判断是否存在分享小程序码
        $qrcode=$userinfo['share_qrcode'];
        if(!$userinfo['share_qrcode']){
            $wxmini=new \app\common\library\xiluhouse\Wxmini;
            $res=$wxmini->getWXacode('user_'.$userinfo['id'], 'pages/home/index/index');
            if($res) {
                $root = '.';
                $filename = md5(mt_rand()).'.png';
                $path = "/uploads/".date('Ymd').'/';

                if (!file_exists($root . $path)) {
                    @mkdir($root . $path, 0777, true);
                }
                $qrcode = $path.$filename;
                if(!get_addon_info('alioss') || get_addon_info('alioss')['state'] != 1){
                   $res = file_put_contents($root.$qrcode,$res);
                }else{
                    Common::uploadAlioss($qrcode, $res);
                }
                $userinfo->userprofile->allowField(true)->save(['share_qrcode'=>cdnurl($qrcode,true)]);
            }

            //unset($userinfo->userprofile);
        }
        if(!$qrcode){
            $qrcode = \app\common\model\xiluhouse\Config::getdatas('wxmini_logo');
        }
        $userinfo['share_qrcode_text']=cdnurl($qrcode,true);
        $userinfo['team_num']=\app\common\model\xiluhouse\User::with('userprofile')->where('userprofile.pid',$this->auth->id)->where('status','normal')->count();

        //是否申请了房东经纪人
        $userinfo->user_auth = UserAuth::where('user_id',$userinfo->id)->find();

        //判断我的身份，获取对应的佣金余额
        $userinfo->profile = $userinfo->userprofile;

        //普通冻结
        $frezze_money1 = OrderDivide::where('puser_id',$userinfo->id)->where('status',2)->sum('puser_money');
        $frezze_money2 = OrderDivide::where('lessor_puser_id',$userinfo->id)->where('status',2)->sum('lessor_puser_money');
        $userinfo->profile->frezze_money = bcadd($frezze_money1,$frezze_money2,2);
        //房东冻结
        $userinfo->profile->frezze_lessor_money = OrderDivide::where('lessor_user_id',$userinfo->id)->where('status',2)->sum('lessor_money');

        //经纪人冻结
        $userinfo->profile->frezze_broker_money = OrderDivide::where('lessor_user_id',$userinfo->id)->where('status',2)->sum('broker_money');

        //代理房源
        $userinfo->agent_rental_count = \app\common\model\xiluhouse\Rental::getAgentCount($userinfo->id);

        //有效客户
        $userinfo->valid_count = 0;

        // 获取积分
        // 今天是否已签到
//        $model=new \app\common\model\xiluhouse\SignLog;
//        $today_sign_exist=$model->where('user_id',$this->auth->id)->whereTime('createtime', 'today')->find();
//        $userinfo['today_is_sign']=false;
//        if($today_sign_exist){
//            $userinfo['today_is_sign']=true;
//        }
//        $exist=$model->where('user_id',$this->auth->id)->whereTime('createtime', 'yesterday')->find();
//        $sign_week_day=0;
//        $init_sign_score=\app\common\model\xiluhouse\Config::getdatas('init_sign_score');
//        $add_sign_score=\app\common\model\xiluhouse\Config::getdatas('add_sign_score');
//        if($exist){
//            $sign_week_day=$exist['sign_week_day'];
//        }
//        $userinfo['now_sign_score']=$init_sign_score+($add_sign_score*$sign_week_day);

        #支付按钮如果关闭，则租户签约完成，当前订单已完成
        $renter_pay_switch = \app\common\model\xiluhouse\Config::getdatas('renter_pay_switch') ?? 0;
        #分销开关
        $renter_retail_switch = \app\common\model\xiluhouse\Config::getdatas('renter_retail_switch') ?? 0;
        $userinfo->renter_pay_switch = $renter_pay_switch;
        $userinfo->renter_retail_switch = $renter_retail_switch;
        $this->success('',$userinfo);
    }

    /**
     * @title 会员身份查询
     *
     * @return int   $msg_open_state   1    通知类型:1=可接收消息,2=不接收消息
     * @return bool   $today_is_sign   false    今天是否已签到
     * @return int   $now_sign_score   0        待获得积分
     */
    public function user_apply()
    {
        $userinfo = \app\common\model\xiluhouse\User::get($this->auth->id,'extension')->hidden(['salt','password','email','loginfailure','loginip','token','level','verification']);
        //是否申请了房东经纪人
         $user_auth_broker = UserAuth::where('user_id',$userinfo->id)->where('check_status','<',2)->where('is_broker',2)->find();
        $userinfo->user_auth = null;
        if($user_auth_broker){
            $userinfo->user_auth = $user_auth_broker;
        }else{
            $user_auth_lessor = UserAuth::where('user_id',$userinfo->id)->where('check_status','<',2)->where('is_broker',1)->find();
            if($user_auth_lessor){
                $userinfo->user_auth = $user_auth_lessor;
            }
        }
        $this->success('',$userinfo);
    }
    /**
     * @title 打开和关闭通知
     * 
     * @return int   $msg_open_state   1    通知类型:1=可接收消息,2=不接收消息 
     */
    public function msgOpenState(){
        $userinfo = \app\common\model\xiluhouse\UserProfile::where('user_id',$this->auth->id)->find();
        if(!$userinfo){
            $this->error('参数错误');
        }
        $now_msg_open_state=$userinfo['msg_open_state']==1?2:1;
        $userinfo->save([
            'msg_open_state'=>$now_msg_open_state,
        ]);
        $this->success('',['msg_open_state'=>$now_msg_open_state]);
    }
    /**
     * @title 个人中心统计
     */
    public function member_statistics(){
        // 我的团队
        $data['team_num']=\app\common\model\xiluhouse\UserProfile::where('pid',$this->auth->id)
                            ->where('status','normal')
                            ->count()?:0;
        // 我的权益
        $data['rights_num']=\app\common\model\xiluhouse\Article::where('classify',5)
                            ->where('status','normal')
                            ->count()?:0;
        // 我的服务
        $data['service_num']=\app\common\model\xiluhouse\AppointLog::where('user_id',$this->auth->id)
                            ->count()?:0;
        // 我的浏览
        $data['view_num']=\app\common\model\xiluhouse\HouseView::where('user_id',$this->auth->id)
                            ->count()?:0;
        $this->success('',$data);
    }

    /**
     * @title 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * @title 修改会员个人信息
     *
     * @param string $avatar   无 头像地址
     * @param string $nickname 无 昵称
     * @param string $gender    0 性别:0=保密,1=男,2=女
     * @param string $bio      无  个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->param('username');
        $nickname = $this->request->param('nickname', '', 'trim,strip_tags,htmlspecialchars');
        $bio = $this->request->param('bio');
        $gender = $this->request->param('gender',0);
        $avatar = $this->request->param('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\xiluhouse\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\xiluhouse\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('该昵称已存在'));
            }
            $user->nickname = $nickname;
        }
        if ($bio) {
            $user->bio = $bio;
        }
        if ($gender) {
            $user->gender = $gender;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }

    /**
     * @title 修改手机号
     *
     * @param string $mobile  无  手机号
     * @param string $captcha  无 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->param('mobile');
        $captcha = $this->request->param('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\xiluhouse\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
}
